import { ElLoading, ElMessage } from "element-plus";
let loadingInstance = null;
// 打开遮罩层
export function uploadFileLoading(content) {
  loadingInstance = ElLoading.service({
    lock: true,
    text: content,
    background: "rgba(0, 0, 0, 0.7)",
  });
}
// 关闭遮罩层
export function uploadFileCloseLoading() {
  loadingInstance.close();
}

// 工具方法
export const uploadType = {
  ready: "ready",
  uploading: "uploading",
  success: "success",
  fail: "fail",
};
export const formatFileSize = (size) => {
  if (size < 1024) {
    return `${size} B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  }
};

export const getFileStatusType = (status) => {
  switch (status) {
    case "ready":
      return "info";
    case "uploading":
      return "warning";
    case "success":
      return "success";
    case "fail":
      return "danger";
    default:
      return "info";
  }
};

export const getFileStatusText = (status) => {
  switch (status) {
    case "ready":
      return "待上传";
    case "uploading":
      return "上传中";
    case "success":
      return "上传成功";
    case "fail":
      return "上传失败";
    default:
      return "未知";
  }
};
// 对象转成指定字符串分隔
export const listToString = (list, separator) => {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].fileUrl) {
      strs += list[i].fileUrl + separator;
    }
  }
  return strs != "" ? strs.slice(0, -1) : "";
};
/**
 * pdf预览
 * @param {*} file
 */
export const handlePdfPreview = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    ElMessage.error("未找到PDF文件地址");
  }
};
/** 下载文件
 * @param {*} file
 */
export const handleDownload = (file) => {
  const link = document.createElement("a");
  link.href = file.url;
  link.download = file.name || "download";
  link.click();
  document.body.removeChild(link);
};

/**
 * 下载文件
 * @param {string} url - 文件的下载地址
 * @param {string} fileName - 下载后的文件名
 */

export function handleDownloadByUrl(url, fileName) {
  fetch(url)
    .then((res) => res.blob())
    .then((blob) => {
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(link.href);
    })
    .catch(() => {
      console.error("下载失败");
    });
}
/**
 *  获取文件唯一字符串（不依赖第三方库）
 * @param {*} file
 * @returns
 */
export function getFileUniqueString(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      // 取前100字节内容做简单 hash
      const arr = new Uint8Array(e.target.result);
      let hash = 0;
      for (let i = 0; i < arr.length; i++) {
        hash = (hash * 31 + arr[i]) % 1000000007;
      }
      resolve(`${file.name}_${file.size}_${file.lastModified}_${hash}`);
    };
    reader.onerror = function () {
      reject("文件读取失败");
    };
    // 只读取前100字节
    reader.readAsArrayBuffer(file.slice(0, 100));
  });
}

/**
 * 传入 File 对象，返回 MD5 字符串
 * 浏览器兼容性不好，慎用
 * @param {*} file
 * @returns
 */
export async function getFileMd5(file) {
  const arrayBuffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest("MD5", arrayBuffer);
  // 转为16进制字符串
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const md5 = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
  return md5;
}
/** 传入 File 对象，返回 SHA-256 字符串
 * @param {*} file
 * @returns
 */
export async function getFileSha256(file) {
  const arrayBuffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest("SHA-256", arrayBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const sha256 = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
  return sha256;
}

export const getFileIdShar256Value = async (file) => {
  const fileId = await getFileSha256(file)
    .then((id) => {
      return id;
    })
    .catch((error) => {
      console.error("Error generating unique file string:", error);
    });
  return fileId;
};

export function uploadFileWithFetch(url, formData, extraData, headers) {
  return new Promise(async (resolve, reject) => {
    try {
      // 添加额外字段
      if (extraData) {
        Object.keys(extraData || {}).forEach((key) => {
          formData.append(key, extraData[key]);
        });
      }
      //console.log(`url------------>`, url);
      const response = await fetch(url, {
        method: "POST",
        headers: headers,
        body: formData,
      });
      if (!response.ok) {
        ElMessage.error("上传失败");
        reject(new Error("上传失败"));
      }
      const data = await response.json();
      resolve(data);
    } catch (error) {
      ElMessage.error("上传失败");
      reject(error);
    }
  });
}
